package com.first.nell.components.form

import android.annotation.SuppressLint
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.first.nell.R
import com.first.nell.base.BaseFormAction
import com.first.nell.components.dialog.PopListAdapter
import com.first.nell.components.dialog.PopListItem
import com.first.nell.data.RevObjInfoPageFieldConfig
import com.first.nell.databinding.ViewFirstNellFormSelectCountryBinding
import com.first.nell.enums.CountryEnum
import com.first.nell.extend.*

/**
<declare-styleable name="FirstNellFormSelect">
<attr name="cwfscountryTitle" format="string" />
<attr name="cwfscountryText" format="string" />
<attr name="cwfscountryHint" format="string" />
<attr name="cwfscountryTitleColor" format="color" />
<attr name="cwfscountryTextColor" format="color" />
<attr name="cwfscountryHintColor" format="color" />
<attr name="cwfscountryTitleSize" format="dimension" />
<attr name="cwfscountryTextSize" format="dimension" />
<attr name="cwfscountryIsTitleBold" format="boolean" />
</declare-styleable>
 * */
class SelectCountryForm : RelativeLayout,
    com.first.nell.components.form.BaseFormAction,
    BaseFormAction {

    private lateinit var vFirstNellRootFirstNellView: View
    lateinit var mFirstNellViewFirstNellBinding: ViewFirstNellFormSelectCountryBinding
    lateinit var mPopListAdapter: PopListAdapter

    private var cwfscountryTitleColor: Int = 0
    private var cwfscountryTextColor: Int = 0
    private var cwfscountryHintColor: Int = 0
    private var cwfscountryTitle: String? = null
    private var cwfscountryText: String? = null
    private var cwfscountryHint: String? = null
    private var cwfscountryTitleSize: Float = 0F
    private var cwfscountryTextSize: Float = 0F
    private var cwfscountryIsTitleBold: Boolean = false

    private var mFirstNellSupportFirstNellFragmentFirstNellManager: FragmentManager? = null
    private var onFirstNellFormFirstNellConfig: RevObjInfoPageFieldConfig? = null
    private var onFirstNellStateFirstNellChangedFirstNellListener: (Int, String) -> Unit =
        { _, _ -> }

    private var mFirstNellTempFirstNellInputFirstNellValue: String = ""
    private var mFirstNellOnFirstNellActionFirstNellClickFirstNellListener: (Int) -> Unit = {}
    private var mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener: (String) -> Unit =
        { _ -> }
    private var mFirstNellOnFirstNellListFirstNellItemFirstNellClickFirstNellListener: (String, String) -> Unit =
        { _, _ -> }
    private val mFirstNellDataFirstNellList = mutableListOf<PopListItem>()

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        attrs?.let {
            context?.let { cxt ->
                val array =
                    cxt.obtainStyledAttributes(attrs, R.styleable.SelectCountryForm)
                cwfscountryTitleColor = array.getColor(
                    R.styleable.SelectCountryForm_cwfscountryTitleColor,
                    ContextCompat.getColor(cxt, R.color.form_title)
                )
                cwfscountryTitle =
                    array.getString(R.styleable.SelectCountryForm_cwfscountryTitle)

                cwfscountryTextColor = array.getColor(
                    R.styleable.SelectCountryForm_cwfscountryTextColor,
                    ContextCompat.getColor(cxt, R.color.main_black)
                )
                cwfscountryText =
                    array.getString(R.styleable.SelectCountryForm_cwfscountryText)

                cwfscountryHintColor = array.getColor(
                    R.styleable.SelectCountryForm_cwfscountryHintColor,
                    ContextCompat.getColor(cxt, R.color.input_hint)
                )
                cwfscountryHint =
                    array.getString(R.styleable.SelectCountryForm_cwfscountryHint)

                cwfscountryTitleSize = array.getDimension(
                    R.styleable.SelectCountryForm_cwfscountryTitleSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_15
                    ).toFloat()
                )

                cwfscountryTextSize = array.getDimension(
                    R.styleable.SelectCountryForm_cwfscountryTextSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_15
                    ).toFloat()
                )

                cwfscountryIsTitleBold = array.getBoolean(
                    R.styleable.SelectCountryForm_cwfscountryIsTitleBold,
                    false
                )

                array.recycle()
            }
        }
        context?.let {
            vFirstNellRootFirstNellView =
                View.inflate(it, R.layout.view_first_nell_form_select_country, this)
            mFirstNellViewFirstNellBinding =
                ViewFirstNellFormSelectCountryBinding.bind(vFirstNellRootFirstNellView)
            initFirstNellSubviews()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initFirstNellSubviews() {
        try {
            mFirstNellViewFirstNellBinding.textFormSelectTitle.text = (cwfscountryTitle)
            mFirstNellViewFirstNellBinding.textFormSelectTitle.setTextColor(cwfscountryTitleColor)
            mFirstNellViewFirstNellBinding.textFormSelectTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                cwfscountryTitleSize
            )

            mFirstNellViewFirstNellBinding.editFormSelect.setText(cwfscountryText)
            mFirstNellViewFirstNellBinding.editFormSelect.setTextColor(cwfscountryTextColor)
            mFirstNellViewFirstNellBinding.editFormSelect.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                cwfscountryTextSize
            )

            mFirstNellViewFirstNellBinding.editFormSelect.hint = (cwfscountryHint)
            mFirstNellViewFirstNellBinding.editFormSelect.setHintTextColor(cwfscountryHintColor)

            mFirstNellViewFirstNellBinding.editFormSelect.addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    //判断是否显示删除按键
                    val tempContent = getFirstNellContent()
                    //判断是否值已经变化
                    try {
                        if (tempContent.isNotBlank()) {
                            if (!mFirstNellTempFirstNellInputFirstNellValue.equals(
                                    tempContent,
                                    false
                                )
                            ) {
                                mFirstNellTempFirstNellInputFirstNellValue = tempContent
                                recordFirstNellSelectFirstNellEvent(tempContent)
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            })

            mFirstNellViewFirstNellBinding.vFormSelectAction.setOnClickListener {
                mFirstNellOnFirstNellActionFirstNellClickFirstNellListener.invoke(0)
                if (mFirstNellDataFirstNellList.isNotEmpty()) {
                    if (mFirstNellViewFirstNellBinding.rlFormSelectDataListBg.visibility == VISIBLE) {
                        mFirstNellViewFirstNellBinding.rlFormSelectDataListBg.visibility = GONE

                    } else {
                        mFirstNellViewFirstNellBinding.rlFormSelectDataListBg.visibility = VISIBLE
                        mPopListAdapter.notifyDataSetChanged()
                    }
                } else {
                    mFirstNellViewFirstNellBinding.rlFormSelectDataListBg.visibility = GONE
                }
            }

            mPopListAdapter =
                PopListAdapter(mFirstNellDataFirstNellList)
            mPopListAdapter.setFirstNellOnFirstNellItemFirstNellClickFirstNellListener { _, cashVistaPopListItem ->
                setFirstNellContent("${cashVistaPopListItem.display}#${cashVistaPopListItem.content}")
                mFirstNellViewFirstNellBinding.rlFormSelectDataListBg.visibility = GONE
                mFirstNellOnFirstNellListFirstNellItemFirstNellClickFirstNellListener.invoke(
                    cashVistaPopListItem.display,
                    cashVistaPopListItem.content
                )
            }

            mFirstNellViewFirstNellBinding.rcFormSelectDataList.layoutManager =
                LinearLayoutManager(context)
            mFirstNellViewFirstNellBinding.rcFormSelectDataList.adapter = mPopListAdapter

            if (cwfscountryIsTitleBold) {
                mFirstNellViewFirstNellBinding.textFormSelectTitle.addFirstNellBoldFirstNellStyle()
            } else {
                mFirstNellViewFirstNellBinding.textFormSelectTitle.addFirstNellNormalFirstNellStyle()
            }

            //增加星号显示
            mFirstNellViewFirstNellBinding.textFormSelectTitle.addFirstNellHighlightFirstNellStyle(
                mutableListOf("*"),
                ContextCompat.getColor(context, R.color.main_red)
            )

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun setFirstNellDetail(detail: String) {
        setFirstNellContent(detail)
    }

    override fun setFirstNellDetailFirstNellColor(detailColor: Int) {

    }

    override fun setFirstNellTitleFirstNellColor(titleColor: Int) {

    }

    override fun setFirstNellContent(content: String) {
        mFirstNellViewFirstNellBinding.editFormSelect.setText(content)
        val splitStart = content.indexOf("#")
        if (splitStart >= 0) {
            val bankCodeAndSplitChar = content.substring(splitStart)
            mFirstNellViewFirstNellBinding.editFormSelect.addFirstNellTipsFirstNellStyle(
                words = bankCodeAndSplitChar,
                sizeSpan = 1F,
                ContextCompat.getColor(context, R.color.transparent)
            )
        }
        if (content.isNotBlank()) {
            mFirstNellViewFirstNellBinding.rlFormSelectContentBg.setBackgroundResource(R.drawable.first_nell_form_input)
            mFirstNellViewFirstNellBinding.textFormSelectErrTip.visibility = GONE
        }
        onFirstNellFormFirstNellConfig?.fillContent = content
        recordFirstNellSelectFirstNellEvent(content.uppercase())
    }

    fun getFirstNellContent(): String {
        return mFirstNellViewFirstNellBinding.editFormSelect.text.toString().trim()
    }

    fun getFirstNellTitle(): String {
        return mFirstNellViewFirstNellBinding.textFormSelectTitle.text.toString().trim()
    }

    override fun setFirstNellTitle(title: String) {
        cwfscountryTitle = title
        mFirstNellViewFirstNellBinding.textFormSelectTitle.text = (cwfscountryTitle)
        //增加星号显示
        mFirstNellViewFirstNellBinding.textFormSelectTitle.addFirstNellHighlightFirstNellStyle(
            mutableListOf("*"),
            ContextCompat.getColor(context, R.color.main_red)
        )
    }

    override fun setFirstNellHint(hint: String) {
        cwfscountryHint = hint
        mFirstNellViewFirstNellBinding.editFormSelect.hint = (cwfscountryHint)
    }

    override fun isFirstNellFormFirstNellCompleted(): Boolean {
        val gcontent = getFirstNellContent()
        if (gcontent.isBlank()) {
            mFirstNellViewFirstNellBinding.rlFormSelectContentBg.setBackgroundResource(R.drawable.first_nell_form_input_error)
            mFirstNellViewFirstNellBinding.textFormSelectErrTip.visibility = VISIBLE
            return false
        }

        mFirstNellViewFirstNellBinding.textFormSelectErrTip.visibility = GONE
        mFirstNellViewFirstNellBinding.rlFormSelectContentBg.setBackgroundResource(R.drawable.first_nell_form_input)
        return true
    }

    override fun isFirstNellFormFirstNellCompletedFirstNellSilent(): Boolean {
        val gcontent = getFirstNellContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }

    override fun setFirstNellFormFirstNellConfig(item: RevObjInfoPageFieldConfig) {
        onFirstNellFormFirstNellConfig = item
        tag = item.paramName
        setFirstNellTitle(item.title.toString())
        setFirstNellHint(item.hint.toString())
        item.fillContent?.let { fillContent ->
            setFirstNellContent(fillContent)
        }
        if (item.needCheckComplete == true) {
            isFirstNellFormFirstNellCompleted()
        }

        mFirstNellDataFirstNellList.clear()
        item.values?.forEach {
            mFirstNellDataFirstNellList.add(
                PopListItem(
                    display = it.title.toString(),
                    content = it.value.toString()
                )
            )
        }
    }

    override fun setFirstNellOnFirstNellStateFirstNellChangedFirstNellListener(listener: (Int, String) -> Unit) {
        onFirstNellStateFirstNellChangedFirstNellListener = listener
    }

    override fun setFirstNellFragmentFirstNellManager(manager: FragmentManager) {
        mFirstNellSupportFirstNellFragmentFirstNellManager = manager
    }

    override fun setFirstNellOnFirstNellActionFirstNellClickFirstNellListener(listener: (Int) -> Unit) {
        mFirstNellOnFirstNellActionFirstNellClickFirstNellListener = listener
    }

    fun setFirstNellOnFirstNellTextFirstNellChangedFirstNellListener(listener: (String) -> Unit) {
        mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener = listener
    }

    fun setFirstNellOnFirstNellListFirstNellItemFirstNellClickFirstNellListener(listener: (String, String) -> Unit) {
        mFirstNellOnFirstNellListFirstNellItemFirstNellClickFirstNellListener = listener
    }

    fun setFirstNellDataFirstNellList(dataList: List<CountryEnum>?) {
        dataList?.let { list ->
            mFirstNellDataFirstNellList.clear()
            list.forEach {
                mFirstNellDataFirstNellList.add(
                    PopListItem(
                        display = it.country,
                        content = it.path
                    )
                )
            }
        }
    }
}